package com.mantru.iotpot.Adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.Log
import android.view.View
import android.widget.ImageView
import com.mantru.iotpot.Adapter.Base.AppAdapter
import com.mantru.iotpot.Adapter.Base.AppHolder
import com.mantru.iotpot.Bean.DishesShowBean
import com.mantru.iotpot.R

class DishesImageAdapter(var context: Context, layoutResId: Int, var data: MutableList<DishesShowBean>): AppAdapter<DishesShowBean>(context, layoutResId, data) {
    private var dishesImageListener: DishesImageListener? = null
    fun setDishesImageListener(dishesImageListener: DishesImageListener?) {
        this.dishesImageListener = dishesImageListener
    }
    interface DishesImageListener {
        fun onClick(position: Int)
    }

    override fun convert(holder: AppHolder?, position: Int, item: DishesShowBean) {

        var image: ImageView? = null
        image = holder?.getView<ImageView>(R.id.adapter_dishes_select)
        holder?.setText(R.id.adapter_dishes_name, item.name)
            ?.setBackground(R.id.adapter_dishes_background, item.image)
            ?.setOnClickListener(R.id.adapter_dishes){
                //显示选择并返回选择照片
                image!!.visibility = View.VISIBLE
                dishesImageListener!!.onClick(position)
            }
    }

    @SuppressLint("NotifyDataSetChanged")
    //刷新数据
    fun updateData(newData: List<DishesShowBean>) {
        (context as? Activity)?.runOnUiThread {
            (mItems as? MutableList)?.apply {
                clear()
                addAll(newData)
            }
            notifyDataSetChanged()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun addData(newData: List<DishesShowBean>) {
        (context as? Activity)?.runOnUiThread {
            (mItems as? MutableList)?.apply {
                // 筛选增量数据（避免重复添加已存在的数据）
                val existingItems = mItems.toSet() // 将现有项转换为集合以便快速查找
                val newItems = newData.filter { it !in existingItems } // 筛选不在现有项中的新项
                addAll(newItems)
                val startPosition = mItems.size
                notifyItemRangeInserted(startPosition, newItems.size)
            }
        }
    }
}